/** 
	固件版本列表页
*/

import React, { Component } from "react";
import GridTable from '../../components/display/gridTable';
import {addFollowUpPerson, userStatusChange, prefixFile, userDemandList} from "../../fetch/fetchApi";
import { Button, Input, Row, Col, Select, Divider, Modal, Form, Upload, Icon, Tooltip, Carousel } from 'antd';
import locale from "antd/lib/date-picker/locale/zh_CN";
import ScModal from '../../components/feedback/scModal';
import {DatePicker, message} from "antd/lib/index";
const Option = Select.Option;
const FormItem = Form.Item;
const {TextArea} = Input;
const { RangePicker } = DatePicker;

class NewBusiness extends Component {
    constructor(props) {
        super(props);
        this.init();
        this.state = {
            data: [],
            pagination: {},
            replyContent: '',
            exportMes: '导出',
            loading: false,
            visible: false,
        };
    }

    componentDidMount() {
        this.fetch({
            isNeedInit: true
        });
    }

    init() {
        this.query = {
            page: 1,
            pagecount: 10
        };
        this.params = {
            text: ''
        };
        this.tableColumns = [
            {
                title: '公司全称',
                dataIndex: 'companyName',
                "key": "companyName",
				className: 'column-nowrap',
            }, {
                title: '企业性质',
                dataIndex: 'property',
                "key": "property",
				className: 'column-nowrap',
            }, {
                title: '公司地址',
                dataIndex: 'companyAddress',
                "key": "companyAddress",
				className: 'column-nowrap',
            }, {
                title: '联系人',
                dataIndex: 'chiefPerson',
                "key": "chiefPerson",
                className: 'column-nowrap'
            }, {
                title: '手机号码',
                dataIndex: 'phone',
                "key": "phone",
                className: 'column-nowrap'
            }, {
                title: '邮箱',
                dataIndex: 'mail',
                "key": "mail",
                className: 'column-nowrap'
            }, {
                title: '接入方式',
                dataIndex: 'joinType',
                "key": "joinType",
                className: 'column-nowrap'
            }, {
                title: '图片附件',
                dataIndex: 'cardLicenseImg',
                key: 'cardLicenseImg',
                className: 'column-nowrap',
                render: (text, record) => (<img onClick={() => this.openThumbModal(record.cardLicenseImg, '图片预览', 0)} style={{height:'80px'}} src={record.cardLicenseImg && record.cardLicenseImg.toString().split(',')[0]}/>)
            }, {
                title: '充电设备信息',
                dataIndex: 'stubInfo',
                "key": "stubInfo",
                className: 'column-nowrap',
                render: (text, record) => (
                    <Tooltip placement="topLeft" title={text} >
                        {text}
                    </Tooltip>)
            }, {
                title: '跟进人姓名',
                dataIndex: 'followUpPerson',
                "key": "followUpPerson",
                className: 'column-nowrap'
            }, {
                title: '状态',
                dataIndex: 'status',
                "key": "status",
                className: 'column-nowrap'
            }, {
                title: '操作',
                key: 'action',
                fixed: 'right',
                width: 100,
                render: (text, record) => (
                    <div className="action-wrap">
                        <span>{record.status === '已完成' ? "---" : (record.status === '已处理' ? "---" : <a href="javascript:void(0);" onClick={() => this.openInputModal(record.key, '填写跟进人')}>填写跟进人</a> )}</span>
                        <Divider type="vertical" />
                       {record.status === '已完成' ? "---" :  <a href="javascript:void(0);" onClick={() => this.changeStatus(record)}>处理完成</a>}

                    </div>
                )
            }
        ];

    }

    // 打开输入modal
    openInputModal (id, title) {
        this.params['id'] = id;
        this.setState({
            width: 520,
            modalTitle: title,
            modalName: 'input'
        }, () => {
            this.setState({
                modalVisible: !0
            });
        });
    }


    // 打开预览
    openThumbModal (imgs, title, type) {
        this.openType = type;
        const imgArr = imgs.toString().split(',');
        const thumbDom = [];
        for (let i of imgArr) {
            i.length && thumbDom.push(<div key={i}><h3><img src={i} /></h3></div>);
        }
        this.setState({
            width: 620,
            modalTitle: title,
            thumbDom: thumbDom,
            modalName: 'thumbPic'
        }, () => {
            this.setState({
                modalVisible: !0
            });
        });
    }

    showModal = () => {
        this.setState({
            visible: true,
        });
    }

    async addPerson () {

        this.setState({
            confirmLoading: !0
        });
        try {
            const resData = await addFollowUpPerson(this.params);
            resData.data.code === '200' && this.queryHandler();
        } catch (e) {
            console.log(e);
        }
    }




    async changeStatus(record) {
        this.params['stubId']  = record.key;
        this.params['text']  = record.status;

        const resData = await userStatusChange(this.params);
        resData.data.code === '200' && this.queryHandler();
    }


    async findUserDemandList() {
        return await userDemandList(this.query);
    }



    queryHandler = () => {
        this.query["page"] = 1;
        this.fetch();
    }

    fetch = (params = {}) => {
        this.setState({
            loading: true
        });
        this.findUserDemandList().then((res) => {
            if (!res) {
                return;
            }
            const pagination = this.state.pagination;
            pagination.total = res.data.pageLimit.totalCount;
            pagination.current = params.current || 1;
            if (params.isNeedInit) {
                pagination.onChange = (page, pageSize) => {
                    this.query["page"] = page;
                    this.query["pagecount"] = pageSize;
                    this.fetch({
                        current: page
                    });
                }
            }
            this.setState({
                loading: false,
                data: res.data.data,
                pagination,
            });
        }).catch((ex) => {
            console.log(ex);
        });
    }

    handleOk = (e) => {
        this.setState({
            visible: false,
        });
    }

    handleCancel = (e) => {
        this.setState({
            visible: false,
        });
    }

    // 数据导出
    async exportData () {
        // 判断导出参数
        if (!this.query.startTime) {
            message.warn('请选择时间', 1);
            return;
        }

        let excelUrl = prefixFile + '/findUserDemandList.do?';
        let paramUrl = '';
        Object.keys(this.query).map( (key) => {
            paramUrl += key + '=' + this.query[key] + '&';
        });
        // 截取掉最后一个&符号
        if(paramUrl.length > 0){
            paramUrl = paramUrl.substr(0,paramUrl.length - 1)
        }

        window.location.href = excelUrl + paramUrl;
    }

    // 选择年份
    onDataChange (e) {
        if (e[1]-e[0] > 7 * 24 * 60 * 6e4) {
            message.warn('选择范围请在7天内', 1);
            this.setState({
                'rangeValue': null
            });
            this.query['startTime'] = '';
            this.query['endTime'] = '';
            return;
        };
        this.setState({
            'rangeValue': e
        });
        this.query['startTime'] = e[0] && e[0].format('YYYY-MM-DD HH:mm:ss').toString();
        this.query['endTime'] = e[1] && e[1].format('YYYY-MM-DD HH:mm:ss').toString();
    }

    // 设置回复内容
    replyInputHandler (e) {
        this.params['followUpPerson'] = e.target.value;
        this.setState({
            'replyContent': this.params['followUpPerson']
        })
    }

    // 取消弹窗
    cancel () {
        this.setState({
            modalVisible: !1,
            confirmLoading: !1,
            replyContent: ''
        });
    }
    render() {
        const formItemLayout = {
            labelCol: {
                span: 4
            },
            wrapperCol: {
                span: 16,
                offset: 1
            },
        };
        const Content = <div className="sc-page-content">
            <div className="page-toolbar">
                <Row gutter={8}>
                    <Col lg={7} xl={7} className="whole-fill">
                        <RangePicker value={this.state.rangeValue}
                                     onChange={this.onDataChange.bind(this)} locale={locale} format="YYYY-MM-DD HH:mm:ss" />
                    </Col>
                    <div  className="button-inlineBlock">
                        <Button type="primary" onClick={this.queryHandler}>查询</Button>
                    </div>
                    <div  className="button-inlineBlock">
                        <Button type="primary" icon="download" onClick={this.exportData.bind(this)}>{this.state.exportMes}</Button>
                    </div>
                </Row>
            </div>
            <div className="page-panel">
                <GridTable postyle="table-center"  data={this.state.data} columns={this.tableColumns} loading={this.state.loading} pagination={this.state.pagination}/>
            </div>
            {this.state.modalName === 'input' && <ScModal
                width={this.state.width}
                modalVisible={this.state.modalVisible}
                modalTitle={this.state.modalTitle}
                modalContent={(<div className="sc-modal-scroll">
                    <div className={'modal-list'}>
                        <TextArea placeholder="请输入跟进人姓名" value={this.state.replyContent} onChange={this.replyInputHandler.bind(this)}></TextArea>
                    </div>
                </div>)}
                handle = {() => this.addPerson().then(() => this.cancel())}
                confirmLoading={this.state.confirmLoading}
                cancel={this.cancel.bind(this)}
            />}
            {this.state.modalName === 'thumbPic' && <ScModal
                width={this.state.width}
                modalVisible={this.state.modalVisible}
                modalTitle={this.state.modalTitle}
                modalContent={(<div className="sc-modal-scroll">
                    <div className={'modal-list'}>
                        <Carousel autoplay>
                            {this.state.thumbDom}
                        </Carousel>
                    </div>
                </div>)}
                cancel={this.cancel.bind(this)}
                footer={null}
            />}
        </div>;

        return Content;
    }
}

export default NewBusiness;